package com.sys.app.web.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sys.app.entity.emum.StatusEnum;
import com.sys.app.entity.sys.*;
import com.sys.app.entity.result.ResultDTO;
import com.sys.app.entity.token.TokenUtil;
import com.sys.app.entity.util.SecrecyUtil;
import com.sys.app.entity.util.StringUtil;
import com.sys.app.service.sys.ISysAccountService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("/login")
public class LoginContorller {
    private ISysAccountService iSysAccountService;
    private static Logger logger = LoggerFactory.getLogger(LoginContorller.class);
    public LoginContorller(ISysAccountService iSysAccountService){
        this.iSysAccountService=iSysAccountService;
    }

    /**
     * 主页首页
     * @return
     */
    @GetMapping("/index.do")
    public ModelAndView index(HttpSession session, HttpServletRequest request)  {
        ModelAndView modelAndView = new ModelAndView("login/index");
        String uuid=UUID.randomUUID().toString();
        session.removeAttribute(myConstants.LOGIN_KEY);
        session.setAttribute(myConstants.LOGIN_KEY, uuid);
        // 设置session时常为5分钟,5分钟没有登录，需要刷新页面
        session.setMaxInactiveInterval(60 * 5);
        modelAndView.addObject(myConstants.LOGIN_KEY,uuid);
        return modelAndView;
    }

    /**
     * 登录
     * @param account 登录用户信息
     * @param captcha 验证码
     * @param session 登录
     * @return
     */
    @PostMapping("/authentication.do")
    @ResponseBody
    public ResultDTO login(SysAccount account,String captcha, HttpServletRequest request,HttpSession session) throws Exception{
        //验证登录信息，必须是通过本系统获取的登录信息
        if(StringUtil.isBlank(account.getLoginKey())||null==session.getAttribute(myConstants.LOGIN_KEY)){
            return ResultDTO.error().result("登录信息过期，请刷新页面重新操作");
        }
        if(!account.getLoginKey().equals(session.getAttribute(myConstants.LOGIN_KEY))){
            return ResultDTO.error().result("登录信息验证错误，请刷新页面重新操作");
        }

        // 验证码
        if (null != session && null != session.getAttribute(myConstants.CAPTCHA_CODE_KEY)) {
            if (StringUtil.isNotBlank(captcha)&&!captcha.equals(session.getAttribute(myConstants.CAPTCHA_CODE_KEY).toString())) {
                session.removeAttribute(myConstants.CAPTCHA_CODE_KEY);
                return ResultDTO.error().result("验证码填写错误，请重新输入");
            }
        } else {
            return ResultDTO.error().result("验证码信息已经过期，请重新输入");
        }
        //验证登陆账号+密码
        if(account==null){
            return ResultDTO.error().result("登录信息不能为空");
        }
        if(StringUtil.isBlank(account.getCode())){
            return ResultDTO.error().result("请输入用户名");
        }
        if(StringUtil.isBlank(account.getPassword())){
            return ResultDTO.error().result("请输入密码");
        }
        //密码加密规则：code+pwssword
        QueryWrapper<SysAccount> queryWrapper=new QueryWrapper<SysAccount>();
        queryWrapper.eq("CODE",account.getCode());
        queryWrapper.eq("STATUS", StatusEnum.VALID.getValue());
        SysAccount userModel=iSysAccountService.getOne(queryWrapper);
//        if(userModel!=null){
//              if(!SecrecyUtil.LoginCheckPwd(account.getCode(),account.getPassword(),userModel.getPassword(),myConstants.MD5_KEY)) {
//                  return ResultDTO.error().result("用户名或者密码错误");
//              }
//        }else{
//            return ResultDTO.error().result("用户名不存在");
//        }
        // 获取ip
        String ip = getIpAddr(request);
        // 获取主机
        String pcName = getHostName(ip);
        //生成token
        String token=TokenUtil.sign(userModel);
        //获取token过期时间戳
        Long expireTime=TokenUtil.getJwtExpiresAt(token);
        session.setAttribute(myConstants.SYS_ACCOUNT_SESSION_KEY, token);
       // 设置session时常为60分钟
       session.setMaxInactiveInterval(60 * 60);
       //删除登录key
        session.removeAttribute(myConstants.LOGIN_KEY);
        Map<String,String> map=new HashMap<>();
        map.put("url","/main/index.do");
        if(!myConstants.AUTHORIZATION_TYPE.equals("session")) {
            map.put("expireTime",expireTime.toString());
            map.put("token", token);
        }else{
            map.put("token", "");
        }
       return ResultDTO.ok().result(map);
    }

    // 获取登录用户ip
    private String getIpAddr(HttpServletRequest request) throws UnknownHostException {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (ip.equals("0:0:0:0:0:0:0:1")) {
            ip = "172.0.0.1";
        }
        return ip;
    }

    // 根据ip获取主机名
    private String getHostName(String ip) throws Exception {
        // 局域网内通过电脑的IP来得到MAC物理地址
        String[] ipstr = ip.split("[.]");
        byte[] by = new byte[4];
        for (int i = 0; i < 4; i++) {
            int m = Integer.parseInt(ipstr[i]);
            byte b = (byte) (m & 0xff);
            by[i] = b;
        }
        InetAddress inet = InetAddress.getByAddress(by);
        String pc = inet.getHostName();
        return pc;
    }

}
